package com.csx.framework.netty.boot.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2023/8/10 周四 19:22
 */

@Component
public class NettyServer {

    private Logger logger = LoggerFactory.getLogger(NettyServer.class);

    // 配置服务端NIO线程组
    private final EventLoopGroup parentGroup = new NioEventLoopGroup();
    private final EventLoopGroup childGroup = new NioEventLoopGroup();

    private Channel channel;

    public ChannelFuture bing(InetSocketAddress address) {

        ChannelFuture channelFuture = null;
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new MyChannelInitializer());
            channelFuture = bootstrap.bind(address).syncUninterruptibly();
            channel = channelFuture.channel();
        }catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if(null != channelFuture && channelFuture.isSuccess()) {
                logger.info("正常");
            }else {
                logger.error("异常");
            }
        }
        return channelFuture;
    }

    public void destroy() {
        if(null == channel) return;
        channel.close();
        childGroup.shutdownGracefully();
        parentGroup.shutdownGracefully();
    }

    public Channel getChannel() {
        return channel;
    }
}
